<!--
 * @Author: hucc
 * @Date: 2021-09-29 11:40:36
 * @LastEditors: hucc
 * @LastEditTime: 2021-10-06 16:54:58
 * @Description: 
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>节流</title>
    <style>
        body {
            height: 2000px;
        }
    </style>
</head>

<body>

</body>
<script>
    //节流：控制高频事件的触发次数 
    // 防抖：获取高频事件的最后一次执行结果
    // let flag = true;
    // window.onscroll = function() {
    //     //console.log("滚起来了")
    //     if (flag) {
    //         setTimeout(() => {
    //             console.log("滚起来了");
    //             flag = true;
    //         }, 500)
    //     }
    //     flag = false
    // }


    window.onscroll = throttle(function() {
        console.log("滚动", this);
    }, 500)

    function throttle(fn, delay) {
        let flag = true;
        return function() {
            if (flag) {
                setTimeout(() => {
                    //console.log(this); 这里箭头函数的this指向window
                    //fn本来的this指向也是window 所以在这里只需要调用fn(),不用改变this指向
                    fn();
                    flag = true;
                }, delay)
            }
            flag = false;
        }
    }
</script>

</html>